package com.sunni;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;

public class MyRealm extends AuthorizingRealm {


    /*认证  登录验证（md5加盐加散列）  账号啊、密码啊 正不正确？*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        /*判断 用户是否存在*/


        /*获取用户名  (前台用户输入的账号名)*/
        String username = (String) token.getPrincipal();

        /*从数据库取，，这里演示写死了*/
        String name = "sunni";
        String password = "8d88fa17cf0ef8e20f3e4280e1b7bd64";


        /*name(数据库去的)  比较  username(用户输入的)，如果没有返回null，会直接报错*/
        if (! name.equals(username)){ //有的话是true, !true, false就是没有嘛
            return null;
        }

        /*如果有，，，在交给Info进一步去比较password*/
        /*为什么给info username呢？ 因为前面username比较name,是一样的，所以这里把username传给info了。传哪个都可，因为值一样。*/
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,ByteSource.Util.bytes("yan"),this.getName());

        return info;
    }

    /*授权  分配权限，可以访问哪些资源*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        /*获取登录用户的信息*/
        Object primaryPrincipal = principals.getPrimaryPrincipal();

        ArrayList<String> roles = new ArrayList<>();
        roles.add("role1");
        roles.add("role2");

        ArrayList<String> permissions = new ArrayList<>();
        permissions.add("user:insert");
        permissions.add("user:update");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }


}
